import { Injectable } from '@nestjs/common';

@Injectable()
export class LoggingPerformanceConfig {
  /**
   * 日志记录性能配置
   */
  static readonly CONFIG = {
    // 批量写入配置
    batchWrite: {
      enabled: true,
      batchSize: 10, // 批量写入大小
      flushInterval: 1000, // 刷新间隔(ms)
      maxWaitTime: 5000 // 最大等待时间(ms)
    },

    // 字段差异分析配置
    fieldDiff: {
      maxDepth: 5, // 最大比较深度
      maxArrayLength: 100, // 最大数组比较长度
      maxObjectKeys: 50, // 最大对象键数量
      enableSmartIgnore: true, // 启用智能忽略
      cacheResults: true, // 缓存比较结果
      cacheTimeout: 300000 // 缓存超时(ms)
    },

    // 敏感数据处理配置
    sensitiveData: {
      autoRedaction: true, // 自动脱敏
      redactionRules: [
        { pattern: /^(ghu|ghp|gho|ghs)_[A-Za-z0-9_]{36,251}$/, replacement: '[GITHUB_TOKEN]' },
        { pattern: /^bearer\s+/i, replacement: '[BEARER_TOKEN]' },
        { pattern: /password/i, replacement: '[PASSWORD]' },
        { pattern: /secret/i, replacement: '[SECRET]' },
        { pattern: /key/i, replacement: '[KEY]' }
      ],
      maxValueLength: 200 // 最大值长度
    },

    // 性能监控配置
    performance: {
      enableMetrics: true, // 启用性能指标
      slowRequestThreshold: 5000, // 慢请求阈值(ms)
      memoryWarningThreshold: 100 * 1024 * 1024, // 内存警告阈值(bytes)
      maxConcurrentLogs: 100, // 最大并发日志数
      enableProfiling: process.env.NODE_ENV === 'development'
    },

    // 存储配置
    storage: {
      compression: true, // 启用压缩
      archiveOlderThan: 30 * 24 * 60 * 60 * 1000, // 归档时间(ms)
      deleteOlderThan: 90 * 24 * 60 * 60 * 1000, // 删除时间(ms)
      maxRecordsPerTable: 1000000, // 每表最大记录数
      enablePartitioning: false // 启用分区（需要数据库支持）
    },

    // 错误处理配置
    errorHandling: {
      maxRetries: 3, // 最大重试次数
      retryDelay: 1000, // 重试延迟(ms)
      circuitBreakerThreshold: 10, // 熔断器阈值
      circuitBreakerTimeout: 30000, // 熔断器超时(ms)
      fallbackToFileSystem: true // 失败时回退到文件系统
    },

    // 查询优化配置
    queries: {
      defaultPageSize: 20,
      maxPageSize: 100,
      enableQueryCache: true,
      queryCacheTimeout: 60000, // 查询缓存超时(ms)
      indexHints: {
        requestLogs: ['IDX_copilot_request_logs_dashboard_query'],
        fieldMappings: ['IDX_copilot_field_mappings_analysis']
      }
    }
  };

  /**
   * 获取批量写入配置
   */
  getBatchWriteConfig() {
    return LoggingPerformanceConfig.CONFIG.batchWrite;
  }

  /**
   * 获取字段差异分析配置
   */
  getFieldDiffConfig() {
    return LoggingPerformanceConfig.CONFIG.fieldDiff;
  }

  /**
   * 获取敏感数据处理配置
   */
  getSensitiveDataConfig() {
    return LoggingPerformanceConfig.CONFIG.sensitiveData;
  }

  /**
   * 获取性能监控配置
   */
  getPerformanceConfig() {
    return LoggingPerformanceConfig.CONFIG.performance;
  }

  /**
   * 获取存储配置
   */
  getStorageConfig() {
    return LoggingPerformanceConfig.CONFIG.storage;
  }

  /**
   * 获取错误处理配置
   */
  getErrorHandlingConfig() {
    return LoggingPerformanceConfig.CONFIG.errorHandling;
  }

  /**
   * 获取查询优化配置
   */
  getQueryConfig() {
    return LoggingPerformanceConfig.CONFIG.queries;
  }

  /**
   * 检查是否启用某个功能
   */
  isFeatureEnabled(feature: string): boolean {
    switch (feature) {
      case 'batchWrite':
        return LoggingPerformanceConfig.CONFIG.batchWrite.enabled;
      case 'autoRedaction':
        return LoggingPerformanceConfig.CONFIG.sensitiveData.autoRedaction;
      case 'enableMetrics':
        return LoggingPerformanceConfig.CONFIG.performance.enableMetrics;
      case 'compression':
        return LoggingPerformanceConfig.CONFIG.storage.compression;
      case 'queryCache':
        return LoggingPerformanceConfig.CONFIG.queries.enableQueryCache;
      default:
        return false;
    }
  }

  /**
   * 动态调整配置（用于运行时优化）
   */
  adjustConfig(path: string, value: any) {
    const parts = path.split('.');
    let config: any = LoggingPerformanceConfig.CONFIG;
    
    for (let i = 0; i < parts.length - 1; i++) {
      config = config[parts[i]];
      if (!config) return false;
    }
    
    const lastKey = parts[parts.length - 1];
    if (config[lastKey] !== undefined) {
      config[lastKey] = value;
      return true;
    }
    
    return false;
  }

  /**
   * 获取当前系统负载建议的配置
   */
  getAdaptiveConfig(): {
    batchSize: number;
    flushInterval: number;
    maxConcurrentLogs: number;
  } {
    // 根据系统负载动态调整配置
    const memoryUsage = process.memoryUsage();
    const isHighMemory = memoryUsage.heapUsed > LoggingPerformanceConfig.CONFIG.performance.memoryWarningThreshold;
    
    return {
      batchSize: isHighMemory ? 5 : LoggingPerformanceConfig.CONFIG.batchWrite.batchSize,
      flushInterval: isHighMemory ? 2000 : LoggingPerformanceConfig.CONFIG.batchWrite.flushInterval,
      maxConcurrentLogs: isHighMemory ? 50 : LoggingPerformanceConfig.CONFIG.performance.maxConcurrentLogs
    };
  }
}